package com.zhang.third.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @title: 从文件读取数据，计算wordcount
 * @author: zhang
 * @date: 2022/4/1 11:51
 */
public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .readTextFile("/Users/apple/IdeaProjects/flink_1.13/src/main/resources/word.txt")
                .flatMap(new Tokenizer())
                .keyBy(new SetKey())
                .reduce(new Sum())
                .print();

        env.execute();
    }

    public static class SetKey implements KeySelector<Tuple2<String, Integer>, String> {
        @Override
        public String getKey(Tuple2<String, Integer> value) throws Exception {
            return value.f0;
        }
    }

    // reduceFunction:只有一个泛型 因为输入、累加器、输出泛型相同
    public static class Sum implements ReduceFunction<Tuple2<String, Integer>> {
        // 两个参数：一个是输入事件，一个是累加器
        @Override
        public Tuple2<String, Integer> reduce(Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) throws Exception {
            //定义输入数据和累加器聚合规则
            return Tuple2.of(value1.f0, value1.f1 + value2.f1);
        }
    }

    public static class Tokenizer implements FlatMapFunction<String, Tuple2<String, Integer>> {
        @Override
        public void flatMap(String in, Collector<Tuple2<String, Integer>> out) throws Exception {
            String[] array = in.split(" ");
            for (String word : array) {
                // 将待发送数据收集到集合里面
                // flink自动将集合中的数据向下游发送
                out.collect(Tuple2.of(
                        word, 1
                ));
            }
        }
    }
}
